package com.lu.dao;

import org.junit.jupiter.api.Assertions;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

public class BaseDao {
/*    private static final String DRIVERNAME = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/NewsManagerSystem";
    private static final String UNAME = "root";
    private static final String PASSWORD = "123456";

    // 获取数据库连接
    public Connection getCon() {
        Connection con = null;
        try {
            Class.forName(DRIVERNAME);
            con = DriverManager.getConnection(URL, UNAME, PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        return con;
    }*/

    public Connection getCon(){
        Connection con = null;
        try {
            Context context = new InitialContext();
            DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/news");
            con = dataSource.getConnection();
        } catch (NamingException | SQLException e) {
            throw new RuntimeException(e);
        }
        return  con;
    }
    
    // 关闭所有对象
    public void closeAll(Connection con, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 通用增删改
    public int executeUpdate(String sql, Object[] params) {
        int result = 0;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1,params[i]);
            }
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con,pstmt,null);
        }
        return result;
    }
   //@Test
    public void testExecuteUpdate(){
        String sql = "insert into news_users(uid,uname,upwd) values(?,?,?)";
        Object[] params ={2,"xiaoming","123456"};
        Assertions.assertTrue(executeUpdate(sql,params)>0);
    }
}
